/*Group 04
José Renato da Silva Bonatelli 7288964
Matheus Martins Teixeira 7277482
Rafael de Paula Pinto Paravia 71522567*/

/*Simulating the Black Scholes Model with a sequential approach of the Monte Carlo algorithm*/
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
#define MAX(A,B) A>B?A:B

int main(void)
{
    const unsigned int A = 1664525, C = 1013904223;
    unsigned int random;
    int i,m;
    double r,v,total,aux,aux2,aux3,s,e,t,temp,*trials;
    scanf(" %lf %lf %lf %lf %lf %d ",&s,&e,&r,&v,&t,&m);
    /*Input:
        s = Stock Price
        e = Strike Price
        r = Interest rate
        v = Volatility
        t = Time to expect
        m = Number of iterations */
    aux = (r-v*v*0.5)*t;
    aux2 = v*sqrt(t);
    aux3 = exp(-r*t);
    random = time(NULL);    /*Initial seed*/
    trials = (double*) malloc(m*sizeof(double));
    if(trials==NULL){printf("Error on memory allocation");exit(-1);}
    total = 0;
    for(i=0; i<m; i++){
        random = random*A+C;        /*Calculating a pseudo-random value*/
        temp = s*exp(aux+aux2*((float)random/UINT_MAX));
        trials[i] = aux3 * (MAX(temp-e,0));
        total += trials[i];
    }
    double mean = total/m;                      /*Calculating the mean */
    total = 0;
    for(i=0; i<m; i++) total+= pow(trials[i]-mean,2);
    double stddev = sqrt(total/m);              /*Standard deviation*/
    double confwidth = 1.96 * stddev / sqrt(m); /*Confidence interval*/
    double confmin = mean - confwidth;          /*Maximum value*/
    double confmax = mean + confwidth;          /*Minimum value*/
    /*Output*/
    printf("S        %lf\nE        %lf\nr        %lf\nsigma    %lf\nT        %lf\nM        %d\n",s,e,r,v,t,m);
    printf("Confidence interval :  (%lf,%lf)\n",confmin,confmax);
    free(trials);
    return 0;
}


